import time, datetime, traceback
from xtquant.xttrader import  XtQuantTraderCallback
from xtquant import xtconstant
from xtquant import xtdata
import requests,json
from typing import List
from 基础配置 import settings
from 组件.notice import show_notification_thread
from 订单监控 import order_watch
import threading
from 公共函数 import get_stock_all, ensure_trade_stats_table, add_trade_stat
import pandas as pd

class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def __init__(self,trader, acc,xt_trader):  # 新增构造函数
        super().__init__()
        self.acc = acc  # 保存交易接口实例
        self.trader = trader
        self.xt_trader = xt_trader  # 保存交易接口实例
        self.order_status = {}  # 记录委托状态：{order_id: {"total_volume": 委托总量, "filled_volume": 已成交量}}
        self.stock_type = {stock["all_code"]: stock["name"] for stock in settings.STOCK_CODE}
        self._lock = threading.Lock()  # 新增锁
        self.open_prices = {}  # 缓存开盘价格
        self.xtdata = xtdata
        self.day_look = settings.DAY_LOOK

    ##系统
    ##初始化
    def on_start(self):
        ##1.获取未成交订单
        wait_orders = self.get_orders()[1]
        ##2.插入到order_status中
        for order in wait_orders:
            self.order_status[order.order_sysid] = {
                "total_volume": order.order_volume,
                "filled_volume": 0,
                "stock_code": order.stock_code,
                "direction": order.direction,
            }
        print(f"初始化完成,当前挂单列表:{self.order_status}")
    ##获取开盘价
    def _get_open_price(self, stock_code: str) -> float:
        """获取股票的开盘价格"""
        try:
            # 如果已经获取过，直接返回
            if stock_code in self.open_prices:
                return self.open_prices[stock_code]
            
            # 获取当日分钟数据
            today = datetime.datetime.now().strftime("%Y%m%d")
            
            # 下载分钟数据
            self.xtdata.download_history_data(
                stock_code=stock_code,
                period="1m",
                start_time=today,
                end_time=today
            )
            time.sleep(0.1)
            
            # 获取数据
            data = xtdata.get_local_data(
                stock_list=[stock_code],
                period='1m',
                start_time=today,
                end_time=today
            )
            
            df = data.get(stock_code) if data else None
            if df is None or df.empty:
                return 0.0
            
            # 识别时间列和价格列
            time_col = next((c for c in df.columns if 'time' in c.lower()), None)
            price_cols = ['open', 'close', 'lastPrice', 'price']
            price_col = next((c for c in price_cols if c in df.columns), None)
            
            if not time_col or not price_col:
                return 0.0
            
            # 时间格式统一处理
            if str(df[time_col].dtype) in ('int64', 'float64'):
                df['__time__'] = pd.to_datetime(df[time_col], unit='ms') + pd.Timedelta(hours=8)
            else:
                try:
                    df['__time__'] = pd.to_datetime(df[time_col], format='%Y%m%d%H%M%S', errors='coerce')
                except Exception:
                    df['__time__'] = pd.to_datetime(df[time_col], errors='coerce')
            
            df = df[df['__time__'].notna()].sort_values('__time__')
            
            # 筛选交易时段内的数据
            market_start = df['__time__'].dt.time >= datetime.time(9, 30)
            market_end = df['__time__'].dt.time <= datetime.time(15, 0)
            market_mask = market_start & market_end
            
            market_data = df[market_mask]
            if market_data.empty:
                return 0.0
            
            # 获取开盘价格（第一笔数据）
            open_price = float(market_data[price_col].iloc[0])
            self.open_prices[stock_code] = open_price
            return open_price
            
        except Exception as e:
            print(f"获取开盘价格失败: {e}")
            return 0.0
    ##检查最近成交订单
    def _check_recent_trades(self, stock_code: str, minutes: int = 5) -> bool:
        """检查指定股票在指定分钟数内是否有成交记录"""
        try:
            # 获取当前时间戳
            current_time = time.time()
            # 计算时间阈值（分钟转换为秒）
            time_threshold = current_time - (minutes * 60)
            
            # 查询所有成交订单
            trades = self.xt_trader.query_stock_trades(self.acc)
            
            # 筛选指定股票的成交订单
            stock_trades = [trade for trade in trades if trade.stock_code == stock_code]
            
            # 检查是否有在时间阈值内的成交记录
            for trade in stock_trades:
                if trade.traded_time >= time_threshold:
                    # 计算时间差
                    time_diff = current_time - trade.traded_time
                    minutes_ago = int(time_diff / 60)
                    seconds_ago = int(time_diff % 60)
                    
                    if self.trader and self.trader.log_callback:
                        self.trader.log_callback(f"发现 {minutes_ago}分{seconds_ago}秒前的成交记录: {trade.traded_price} {trade.traded_volume}")
                    return True
            
            return False
            
        except Exception as e:
            if self.trader and self.trader.log_callback:
                self.trader.log_callback(f"检查最近成交记录失败: {e}")
            return False
    ##获取最新价
    def _get_now_price(self, stock_code: str) -> float:
        # start_time = time.time()  # 记录开始时间
        current_price = 0.0
        # 获取最新tick数据
        tick_data = self.xtdata.get_full_tick([stock_code])
        # 安全地获取价格数据
        if stock_code in tick_data:
            stock_data = tick_data[stock_code]
            # 检查数据结构并安全获取价格
            if isinstance(stock_data, dict):
                # 如果返回的是字典格式
                current_price = stock_data.get('lastPrice', 0.0)
            elif isinstance(stock_data, list) and len(stock_data) > 0:
                # 如果返回的是列表格式
                if isinstance(stock_data[0], dict):
                    current_price = stock_data[0].get('lastPrice', 0.0)
                else:
                    current_price = stock_data[0] if stock_data[0] else 0.0

        # end_time = time.time()  # 记录结束时间
        # execution_time = (end_time - start_time) * 1000  # 转换为毫秒
        # print(f"get_last_price 执行时间: {execution_time:.2f} 毫秒")
        return current_price
    ##连接断开
    def on_disconnected(self):
        print(datetime.datetime.now(), '连接断开')
        show_notification_thread("系统", "连接断开")
    ##交易
    def is_after_12pm(self):
        """判断当前时间是否在中午12点之后"""
        now = datetime.datetime.now().time()  # 获取当前时间（只取时间部分）
        if self.day_look <= 3:
            noon = datetime.time(11, 0, 0)  # 创建11点的时间对象
        else:
            noon = datetime.time(12, 0, 0)  # 创建12点的时间对象
        return now > noon
    ##成交回调
    def on_stock_trade(self, trade):
        """成交回调（检查是否完全成交）"""
        order_id = trade.order_sysid
        stock_span = {stock["all_code"]: stock["span"] for stock in settings.STOCK_CODE}
        span = stock_span.get(trade.stock_code)
        stock_name = self.stock_type.get(trade.stock_code)
        if order_id not in self.order_status:
            return
        # 更新已成交量
        self.order_status[order_id]["filled_volume"] += trade.traded_volume
        # 检查是否完全成交
        status = self.order_status[order_id]
        if status["filled_volume"] >= status["total_volume"]:
            direction = ""
            print(
                f"[完全成交] 委托单: {order_id}, "
                f"股票: {status['stock_code']}, "
                f"方向: {status['direction']}, "
                f"总量: {status['total_volume']}, "
                f"成交价: {trade.traded_price},"
                f"备注: {trade.order_remark}"
            )
            # 判断原方向并挂反手单
            fanshou = True
            # if trade.order_remark == "自动平仓":
            #     print("自动平仓不挂反手单")
            #     fanshou = False
            #

            if fanshou:
                if trade.order_type == 23:  # 原方向为买入，则反手卖出
                    direction = "买入"
                    if status['stock_code'] == "513130.SH" or status['stock_code'] == "513060.SH" or status['stock_code'] == "159509.SZ":
                        order_remark = {
                            "buy_id": order_id,
                            "sell_type": 2,##1为普通单2为区间单
                            "order_type": 2,##
                            "buy_price": trade.traded_price,
                        }
                        order_remark_string = json.dumps(order_remark, ensure_ascii=False)
                        price = float(trade.traded_price) + float(span)
                        self.place_reverse_order(
                            stock_code=status['stock_code'],
                            price=price,  # 市价单（或指定价格）
                            volume=status['total_volume'],
                            direction=xtconstant.STOCK_SELL,  # 卖出
                            order_remark=order_remark_string
                        )
                    else:
                        order_remark = {
                            "buy_id": order_id,
                            "sell_type": 1,
                            "order_type": 1,##1级止盈
                            "buy_price": trade.traded_price,
                        }
                        order_remark_string = json.dumps(order_remark, ensure_ascii=False)

                        if self.is_after_12pm():
                            up = 1
                        else:
                            ##如果是上午可以设置为0.2%
                            up = 2

                        ##挂两单
                        price = float(trade.traded_price) + float(span)*up
                        self.place_reverse_order(
                            stock_code=status['stock_code'],
                            price=price,  # 市价单（或指定价格）
                            volume=status['total_volume']*0.5,
                            direction=xtconstant.STOCK_SELL,  # 卖出
                            order_remark=order_remark_string
                        )
                        order_remark = {
                            "buy_id": order_id,
                            "sell_type": 1,
                            "order_type": 2,##2级止盈
                            "buy_price": trade.traded_price,
                        }
                        order_remark_string = json.dumps(order_remark, ensure_ascii=False)
                        price = float(trade.traded_price) + float(span)*(up+1)
                        self.place_reverse_order(
                            stock_code=status['stock_code'],
                            price=price,  # 市价单（或指定价格）
                            volume=status['total_volume']*0.5,
                            direction=xtconstant.STOCK_SELL,  # 卖出
                            order_remark=order_remark_string
                        )

                elif trade.order_type == 24:  # 原方向为卖出，则反手买入
                    if status['sell_type'] == 1:
                        print("再次反手单不挂买入")
                    else:
                        direction = "卖出"
                        price = float(trade.traded_price) - float(span)
                        self.place_reverse_order(
                            stock_code=status['stock_code'],
                            price=price,  # 市价单（或指定价格）
                            volume=status['total_volume'],
                            direction=xtconstant.STOCK_BUY,  # 买入
                            order_remark="反手买入"
                        )
            # 移除已完成的委托
            title = f"委托单{order_id}成交"
            msg = f"{stock_name}{direction}成交,数量{status['total_volume']}"
            show_notification_thread(title, msg)
            self.order_status.pop(order_id)
    ##查询
    def get_orders(self):
        # 查询当前账户的所有委托单
        # self.trader.log_callback("查询当前账户的所有委托单")
        orders = self.xt_trader.query_stock_orders(self.acc)
        # 筛选已成交的委托单（根据状态字段）
        filled_orders = [
            order for order in orders
            if order.order_status in [56]  # 已经成交
        ]

        no_filled_orders = [
            order for order in orders
            if order.order_status in [50]  # 待成交
        ]
        # 按 order_time 升序排序（从早到晚）
        filled_orders_sorted = sorted(filled_orders, key=lambda x: x.order_time, reverse=True)

        for order in filled_orders_sorted:
            dt = datetime.datetime.fromtimestamp(order.order_time)
            formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")
            # print(f"原始id: {order.order_sysid}")
            # print(f"股票编号: {order.stock_code}")
            # print(f"成交价格: {order.traded_price}")
            # print(f"方向: {order.order_type}")
            # print(f"数量: {order.traded_volume}")
            # print(f"报单时间: {formatted_time}")
            # print(f"----------------------------------")
        stocks = get_stock_all()
        return filled_orders_sorted,no_filled_orders,stocks
    ##普通下单
    def place_reverse_order(self, stock_code, price, volume, direction, order_remark):
        try:
            order_id = self.xt_trader.order_stock_async(self.acc, stock_code, direction, volume,xtconstant.FIX_PRICE, price, '策略名称', order_remark)
            print(f"订单已提交，委托ID: {order_id}")
            return order_id
        except Exception as e:
            print(f"挂单失败: {e}")
            show_notification_thread("交易", "挂单失败")
            traceback.print_exc()
    ##市价下单【迅投市价,存在滑点】
    def place_market_order2(self, stock_code, volume, direction, order_remark):
        try:
            ##如果有相同股票的待买入挂单则不买入
            # 获取当前待成交订单
            _, no_filled_orders, _ = self.get_orders()

            # 检查是否有相同股票的待买入挂单（只检查买入单）
            for order in no_filled_orders:
                if order.stock_code == stock_code and order.direction == xtconstant.STOCK_BUY:
                    if self.trader and self.trader.log_callback:
                        self.trader.log_callback(f"股票 {stock_code} 已有待成交买入挂单，跳过买入")
                    return False

            # 如果没有相同股票的待买入挂单，则继续下单
            order_id = self.xt_trader.order_stock_async(self.acc, stock_code, direction, volume,
                                                        xtconstant.LATEST_PRICE, 0, "市价", order_remark)
            if self.trader and self.trader.log_callback:
                self.trader.log_callback(f"市价单提交成功: {stock_code}, 数量 {volume}, ID {order_id}")
            return order_id
        except Exception as e:
            if self.trader and self.trader.log_callback:
                self.trader.log_callback(f"市价单提交失败: {e}")
            traceback.print_exc()
            return False
    ##市价下单2【卖一价格限价单】
    def place_market_order(self, stock_code, volume, direction, order_remark,current_price:float = 0):
        try:
            ##如果有相同股票的待买入挂单则不买入
            # 获取当前待成交订单
            _, no_filled_orders, _ = self.get_orders()

            # 检查是否有相同股票的待买入挂单（只检查买入单）
            for order in no_filled_orders:
                ##这里判断是否是1笔转还是一直挂单
                ##改成10分钟内有挂单,则不买
                ##if order.stock_code == stock_code and order.direction == xtconstant.STOCK_BUY:
                if order.direction == xtconstant.STOCK_BUY:
                    if order.stock_code == stock_code:
                        if self.trader and self.trader.log_callback:
                            self.trader.log_callback(f"股票 {stock_code} 已有待成交买入挂单，跳过买入")
                        return False
            
            ##检查最近的相同stock_code的成交订单,如果有5分钟内的订单，则不买入
            recent_trades = self._check_recent_trades(stock_code, minutes=5)
            if recent_trades and direction == xtconstant.STOCK_BUY:
                if self.trader and self.trader.log_callback:
                    self.trader.log_callback(f"股票 {stock_code} 在5分钟内有成交记录，跳过买入")
                return False
            
            
            tick_price = current_price
            now_price = self._get_now_price(stock_code)
            open_price = self._get_open_price(stock_code)
            price = now_price
            ##获取股票当前的价格
            try:
                if current_price > 0:
                    if direction == xtconstant.STOCK_BUY:
                        ##没拿到实时价格用tick价
                        price = tick_price
                        # 如果跌就低一档买入
                        if tick_price < open_price:
                            price = tick_price
                        if tick_price > now_price > 0:
                            price = now_price

                        ##比较缓慢的股票再减少一档试试
                        if stock_code == "513130.SH" or stock_code == "513060.SH" or stock_code == "159509.SZ" :
                            price = tick_price - 0.001 ##科技/医疗
                            price = now_price
                        else:
                            if self.is_after_12pm():
                                ##下午降一档买入
                                ##price = price -0.001
                                pass

                        print(f"买入股票:{stock_code},传入tick价格:{tick_price},当前价格:{now_price},开盘价格:{open_price},实际下单价格:{price}")

                else:
                    # 如果获取不到价格，使用市价单
                    print(f"无法获取股票 {stock_code} 当前价格")
                    return self.place_market_order2(stock_code, volume, direction, order_remark)
                    
            except Exception as e:
                # 如果获取价格失败，使用市价单
                print(f"获取价格失败: {e}")
                return self.place_market_order2(stock_code, volume, direction, order_remark)
            
            # 如果没有相同股票的待买入挂单，则继续下单
            order_id = self.place_reverse_order(
                stock_code=stock_code,
                price=price,  # 使用计算出的价格
                volume=volume,
                direction=direction,
                order_remark=order_remark
            )
            if self.trader and self.trader.log_callback:
                self.trader.log_callback(f"限价单提交成功: {stock_code}, 数量 {volume}, 价格 {price}, ID {order_id}")
            return order_id
        except Exception as e:
            if self.trader and self.trader.log_callback:
                self.trader.log_callback(f"限价单提交失败: {e}")
            traceback.print_exc()
            return False
    ##平仓下单
    def modify_to_market_order(self, order_sysid):
        try:
            # 1. 先获取原委托信息（在撤单之前）
            orders = self.get_orders()[1]
            original_order = None
            for order in orders:
                if order.order_sysid == order_sysid:
                    original_order = order
                    break

            if not original_order:
                self.trader.log_callback(f"未找到委托单，order_sysid: {order_sysid}")
                show_notification_thread("交易", f"平仓失败：未找到委托单 {order_sysid}")
                return False

            # 2. 保存原委托信息
            stock_code = original_order.stock_code
            volume = original_order.order_volume - original_order.traded_volume  # 使用未成交数量
            order_remark = original_order.order_remark
            direction = xtconstant.STOCK_SELL if original_order.order_type == 24 else xtconstant.STOCK_BUY

            self.trader.log_callback(f"开始平仓流程 原始ID:{order_sysid} {stock_code} 方向:{direction} 数量:{volume}")

            # 3. 撤掉原委托
            market = xtconstant.SH_MARKET if stock_code.startswith('60') else xtconstant.SZ_MARKET
            cancel_result = self.xt_trader.cancel_order_stock_sysid(
                account=self.acc,
                market=market,
                sysid=order_sysid
            )

            if cancel_result == -1:
                self.trader.log_callback(f"撤单失败，order_sysid: {order_sysid}")
                show_notification_thread("交易", f"平仓失败：撤单失败 {order_sysid}")
                return False

            # 4. 轮询检查撤单是否完成（最多等待3秒）
            max_wait_time = 3  # 秒
            check_interval = 0.3  # 检查间隔
            start_time = time.time()

            while time.time() - start_time < max_wait_time:
                # 检查委托状态
                orders = self.get_orders()[1]
                order_exists = any(order.order_sysid == order_sysid for order in orders)

                if not order_exists:
                    # 5. 确认撤单成功后，提交新的市价单
                    order_id = self.place_market_order(stock_code, volume, direction, order_remark)
                    if order_id:
                        self.trader.log_callback(f"平仓成功 新委托ID:{order_id} {stock_code} {direction} {volume}")
                        stock_name = self.stock_type.get(stock_code)
                        show_notification_thread("交易", f"{stock_name}平仓")
                        return order_id
                    else:
                        self.trader.log_callback(f"平仓下单失败 {stock_code} {direction} {volume}")
                        show_notification_thread("交易", f"平仓下单失败")
                        return False

                time.sleep(check_interval)

            # 超时处理
            self.trader.log_callback(f"平仓超时：撤单状态未确认 {order_sysid}")
            show_notification_thread("交易", f"撤单未完成 {order_sysid}")
            return False

        except Exception as e:
            error_msg = f"平仓异常: {str(e)}"
            self.trader.log_callback(error_msg)
            show_notification_thread("交易", error_msg)
            traceback.print_exc()
            return False
    ##修改订单金额
    def mod_order_price(self, order_sysid,new_price,new_remark_string:str = ""):
        try:
            # 1. 先获取原委托信息（在撤单之前）
            orders = self.get_orders()[1]
            original_order = None
            for order in orders:
                if order.order_sysid == order_sysid:
                    original_order = order
                    break
            if not original_order:
                return False

            # 2. 保存原委托信息
            stock_code = original_order.stock_code
            volume = original_order.order_volume - original_order.traded_volume  # 使用未成交数量
            if new_remark_string:
                order_remark = new_remark_string
            else:
                order_remark = original_order.order_remark
            direction = xtconstant.STOCK_SELL if original_order.order_type == 24 else xtconstant.STOCK_BUY


            # 3. 撤掉原委托
            market = xtconstant.SH_MARKET if stock_code.startswith('60') else xtconstant.SZ_MARKET
            cancel_result = self.xt_trader.cancel_order_stock_sysid(account=self.acc,market=market,sysid=order_sysid)
            if cancel_result == -1:
                self.trader.log_callback(f"撤单失败，order_sysid: {order_sysid}")
                return False

            # 4. 轮询检查撤单是否完成（最多等待3秒）
            max_wait_time = 3  # 秒
            check_interval = 0.3  # 检查间隔
            start_time = time.time()

            while time.time() - start_time < max_wait_time:
                # 检查委托状态
                orders = self.get_orders()[1]
                order_exists = any(order.order_sysid == order_sysid for order in orders)

                if not order_exists:
                    # 5. 确认撤单成功后，提交新的市价单
                    order_id = self.place_reverse_order(stock_code, new_price, volume, direction, order_remark)
                    if order_id:
                        self.trader.log_callback(f"修改单价成功 新委托ID:{order_id} {stock_code} {direction} {volume}")
                        stock_name = self.stock_type.get(stock_code)
                        show_notification_thread("交易", f"{stock_name}改价成功")
                        return order_id
                    else:
                        show_notification_thread("交易", f"修改单价成功失败")
                        return False

                time.sleep(check_interval)

            # 超时处理
            self.trader.log_callback(f"修改超时：撤单状态未确认 {order_sysid}")
            show_notification_thread("交易", f"修改未完成 {order_sysid}")
            return False

        except Exception as e:
            error_msg = f"平仓异常: {str(e)}"
            self.trader.log_callback(error_msg)
            show_notification_thread("交易", error_msg)
            traceback.print_exc()
            return False
    ##按照股票代码平仓所有卖单
    def cancel_all_sell_orders(self, stock_code):
        if stock_code == "513120.SH":
            print("创新药执行平仓")
            orders = self.get_orders()[1]
            for order in orders:
                if order.stock_code == stock_code and order.direction == xtconstant.STOCK_SELL:
                    self.modify_to_market_order(order.order_sysid)

    ##异步撤单
    def cancel_order(self,order_sysid):
        self.xt_trader.cancel_order_stock_sysid_async(self.acc, xtconstant.SH_MARKET, order_sysid)
    ##下单完成推送
    def on_stock_order(self, order):
        print(
            f"------------订单信息-------------"
            f"[下单] : {order.order_sysid}, "
            f"股票: {order.stock_code}, "
            f"方向: {order.order_type}, "
            f"总量: {order.order_volume}, "
            f"委托价: {order.price}"
            f"状态: {order.order_status}"
            f"------------订单信息-------------"
        )

        if order.order_status == 50:
            self.order_status[order.order_sysid] = {
                "total_volume": order.order_volume,
                "filled_volume": 0,
                "stock_code": order.stock_code,
                "direction": order.direction,
            }
            print(f"已挂单{order.order_sysid}")
            print(self.order_status)
            print("--------------------------------------------------")
        if order.order_status == 54:
            self.order_status.pop(order.order_sysid)
            print(f"已撤单{order.order_sysid}")
            print(self.order_status)
            print("--------------------------------------------------")
    ##下单报错
    def on_order_error(self, order_error):
        ##show_notification_thread("交易", "委托报错回调")
        self.trader.log_callback(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}")
    ##订单检测
    def look_orders(self):
        order_watch(self)

    ##保存
    ##判断是否为有效JSON
    def _is_valid_json(self, text) -> bool:
        """判断字符串是否为有效的JSON格式"""
        if not text or not isinstance(text, str):
            return False
        try:
            json.loads(text)
            return True
        except (json.JSONDecodeError, TypeError, ValueError):
            return False
    
    ##安全获取JSON字符串
    def _safe_json_string(self, text) -> str:
        print(f"{text}")
        if text == "自动平仓":
            return "{}"

        if not text:
            return "{}"  # 返回空JSON对象而不是空字符串
        
        if isinstance(text, str):
            if self._is_valid_json(text):
                return text
            else:
                # 如果不是有效JSON，尝试转义特殊字符
                try:
                    # 将字符串作为JSON字符串值处理
                    escaped_text = json.dumps(text, ensure_ascii=False)
                    return escaped_text
                except:
                    return "{}"
        else:
            # 如果不是字符串，尝试转换为JSON
            try:
                return json.dumps(text, ensure_ascii=False)
            except:
                return "{}"
    
    ##转换数据源
    def convert_to_test_order_create(self, order, avg_price=None, total_volume=None, traded_time=None) -> dict:
        """将迅投订单格式转换为API需要的格式
        
        Args:
            order: 订单对象
            avg_price: 加权平均价格（合并订单时使用）
            total_volume: 合并后的总数量
            traded_time: 最后成交时间
        """
        # 使用传入的参数或订单原始值
        price = avg_price if avg_price is not None else order.traded_price
        volume = total_volume if total_volume is not None else order.traded_volume
        time_stamp = traded_time if traded_time is not None else order.traded_time
        
        dt = datetime.datetime.fromtimestamp(time_stamp)
        formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")

        return {
            "cod": order.stock_code.split('.')[0],
            "val": float(price),
            "cnt": int(volume),
            "dir": "买" if order.order_type == 23 else "卖",
            "dte": formatted_time,
            "sid": 0,  # 默认没有关联ID
            "flg": "未关联",
            "jlr": 0.0,
            "cje": float(price) * float(volume),
            "fse": float(price) * float(volume),
            "ghf": 0.0,
            "sxf": 0.0,
            "yhs": 0.0,
            "remark":self._safe_json_string(order.order_remark),
            "order_id":order.order_sysid
            # 其他必要字段...
        }
    ##保存订单至本地
    def save_orders(self):
        """获取并保存订单到远程数据库"""
        # 查询当前账户的所有成交单
        trades = self.xt_trader.query_stock_trades(self.acc)

        # 按 order_sysid 分组合并订单
        merged_orders = {}
        for trade in trades:
            order_id = trade.order_sysid
            
            if order_id not in merged_orders:
                # 第一笔订单，直接存储
                merged_orders[order_id] = {
                    'trade': trade,
                    'total_volume': trade.traded_volume,
                    'total_amount': trade.traded_price * trade.traded_volume,
                    'last_time': trade.traded_time
                }
            else:
                # 合并相同 order_sysid 的订单
                merged = merged_orders[order_id]
                merged['total_volume'] += trade.traded_volume
                merged['total_amount'] += trade.traded_price * trade.traded_volume
                # 使用最后一笔的时间
                if trade.traded_time > merged['last_time']:
                    merged['last_time'] = trade.traded_time
        
        # 转换合并后的订单格式
        orders_to_send = []
        for order_id, merged_data in merged_orders.items():
            # 计算加权平均价格
            avg_price = merged_data['total_amount'] / merged_data['total_volume']
            orders_to_send.append(
                self.convert_to_test_order_create(
                    merged_data['trade'], 
                    avg_price, 
                    merged_data['total_volume'],
                    merged_data['last_time']
                )
            )
        
        # 按时间排序
        orders_to_send = sorted(orders_to_send, key=lambda x: x['dte'])
        
        # 发送到API
        success = self.send_orders_to_api(orders_to_send)
        if success:
            msg = f"成功保存了{len(orders_to_send)}条订单（合并前{len(trades)}笔）"
            print(msg)
            # show_notification_thread("订单", msg)

        else:
            print("保存订单失败")

        return success

    ##发送订单数据
    def send_orders_to_api(self, orders: List[dict]) -> bool:
        """发送订单数据到远程API（同步版本）"""
        api_url = settings.API
        headers = {"Content-Type": "application/json"}

        try:
            response = requests.post(api_url, json=orders, headers=headers)
            if response.status_code == 200:
                result = response.json()
                return result.get("code", 400) == 200
            return False
        except requests.exceptions.RequestException as e:
            print(f"API请求错误: {e}")
            return False
        except ValueError as e:
            print(f"JSON解析错误: {e}")
            return False

    ##其他
    ##获取最后一笔订单
    def get_last_trade(self):
        trades = self.xt_trader.query_stock_trades(self.acc)
        if trades:
            stock_name = self.stock_type.get(trades[-1].stock_code)
            msg = f"[最新成交]: {stock_name} {trades[-1].traded_price} {trades[-1].traded_volume} {trades[-1].direction} {trades[-1].traded_time} {trades[-1].order_id} {trades[-1].traded_id} {trades[-1].order_type}"
            print(msg)
            self.trader.log_callback(msg)
        else:
            msg = "暂无成交订单"
            print(msg)
            self.trader.log_callback(msg)
    ##关闭
    def cleanup(self):
        # 关闭交易连接等清理工作
        if hasattr(self, 'xt_trader'):
            self.xt_trader.stop()
    ##当日订单统计
    def all_orders(self):
        # 查询当前账户的所有成交单
        trades = self.xt_trader.query_stock_trades(self.acc)

        # 按时间排序
        sorted_trades = sorted(trades, key=lambda x: x.traded_time)

        # 初始化统计
        success_count = 0
        fail_count = 0
        buy_trades = {}  # 存储买入订单 {buy_id: buy_trade}
        sell_trades = {}  # 存储卖出订单 {buy_id: [sell_trades]}
        completed_trades = {}  # 存储已完成的交易对 {buy_id: {buy_trade, sell_trades, total_profit}}

        # 确保统计表存在
        try:
            ensure_trade_stats_table()
        except Exception:
            pass

        # 按时间顺序处理所有交易
        for trade in sorted_trades:
            stock_code = trade.stock_code
            order_type = trade.order_type

            if order_type == 23:  # 买入
                # 买入订单直接存储，使用order_sysid作为buy_id
                buy_trades[trade.order_sysid] = trade
                print(f"📥 记录买入订单: {stock_code} ID:{trade.order_sysid} 价格:{trade.traded_price} 数量:{trade.traded_volume}")

            elif order_type == 24:  # 卖出
                # 解析卖出订单的备注，获取buy_id
                buy_id = None
                order_type_level = 1  # 默认1级止盈
                try:
                    if trade.order_remark:
                        remark = json.loads(trade.order_remark)
                        buy_id = remark.get("buy_id")
                        order_type_level = remark.get("order_type", 1)
                except (json.JSONDecodeError, KeyError) as e:
                    print(f"⚠️  解析卖出订单备注失败: {trade.order_remark}, 错误: {e}")
                    continue

                if buy_id and buy_id in buy_trades:
                    # 将卖出订单关联到对应的买入订单
                    if buy_id not in sell_trades:
                        sell_trades[buy_id] = []
                    sell_trades[buy_id].append(trade)
                    print(f"📤 记录卖出订单: {stock_code} 买入ID:{buy_id} 卖出价:{trade.traded_price} 数量:{trade.traded_volume} 等级:{order_type_level}")
                else:
                    print(f"⚠️  未找到对应的买入订单: {stock_code} 买入ID:{buy_id} 卖出价:{trade.traded_price}")

        # 处理已完成的交易对
        for buy_id, buy_trade in buy_trades.items():
            if buy_id in sell_trades and sell_trades[buy_id]:
                sell_list = sell_trades[buy_id]
                stock_code = buy_trade.stock_code
                
                # 计算总盈利
                total_profit = 0
                total_sell_volume = 0
                all_success = True
                
                print(f"\n🔍 分析交易对: {stock_code} 买入ID:{buy_id}")
                print(f"   买入: 价格:{buy_trade.traded_price} 数量:{buy_trade.traded_volume}")
                
                for sell_trade in sell_list:
                    sell_profit = (sell_trade.traded_price - buy_trade.traded_price) * sell_trade.traded_volume
                    total_profit += sell_profit
                    total_sell_volume += sell_trade.traded_volume
                    
                    # 判断单笔卖出是否成功
                    is_success = sell_trade.traded_price >= buy_trade.traded_price
                    if not is_success:
                        all_success = False
                    
                    print(f"   卖出: 价格:{sell_trade.traded_price} 数量:{sell_trade.traded_volume} 盈利:{sell_profit:.2f} {'✅' if is_success else '❌'}")
                
                # 检查是否完全卖出
                if total_sell_volume >= buy_trade.traded_volume:
                    # 完全卖出，记录交易结果
                    if all_success:
                        success_count += 1
                        print(f"✅ 完全成功交易: {stock_code} 总盈利:{total_profit:.2f}")
                    else:
                        fail_count += 1
                        print(f"❌ 完全失败交易: {stock_code} 总亏损:{abs(total_profit):.2f}")
                    
                    # 保存到统计表
                    try:
                        # 使用最后一笔卖出的时间作为交易完成时间
                        last_sell = sell_list[-1]
                        analysis = self.calculate_max_price_after_stop_loss(stock_code, last_sell.traded_time, last_sell.traded_price)
                        
                        add_trade_stat({
                            "date": datetime.datetime.fromtimestamp(last_sell.traded_time).strftime("%Y-%m-%d"),
                            "stock_code": stock_code,
                            "buy_price": float(buy_trade.traded_price),
                            "sell_price": float(sum(s.traded_price * s.traded_volume for s in sell_list) / total_sell_volume),  # 加权平均卖出价
                            "volume": int(total_sell_volume),
                            "success": all_success,
                            "profit": float(total_profit),
                            "buy_time": datetime.datetime.fromtimestamp(buy_trade.traded_time).strftime("%Y-%m-%d %H:%M:%S"),
                            "sell_time": datetime.datetime.fromtimestamp(last_sell.traded_time).strftime("%Y-%m-%d %H:%M:%S"),
                            "order_sysid": str(buy_id),
                            "high_5m": analysis.get("high_5m") if analysis else None,
                            "low_5m": analysis.get("low_5m") if analysis else None,
                            "last_5m": analysis.get("last_5m") if analysis else None,
                            "points_5m": analysis.get("points_5m") if analysis else None,
                            "remark": f"买入ID:{buy_id},卖出笔数:{len(sell_list)}"
                        })
                    except Exception as e:
                        print(f"❌ 保存交易统计失败: {e}")
                        pass
                    
                    completed_trades[buy_id] = {
                        'buy_trade': buy_trade,
                        'sell_trades': sell_list,
                        'total_profit': total_profit,
                        'success': all_success
                    }
                else:
                    print(f"⚠️  未完全卖出: {stock_code} 买入:{buy_trade.traded_volume} 卖出:{total_sell_volume}")

        # 输出统计结果
        print(f"\n📊 交易统计结果:")
        print(f"成功交易次数: {success_count}")
        print(f"失败交易次数: {fail_count}")
        print(f"总交易次数: {success_count + fail_count}")
        if success_count + fail_count > 0:
            success_rate = success_count / (success_count + fail_count) * 100
            print(f"成功率: {success_rate:.2f}%")

        return {
            'success_count': success_count,
            'fail_count': fail_count,
            'completed_trades': completed_trades,
            'pending_buys': {k: v for k, v in buy_trades.items() if k not in completed_trades}
        }

    def calculate_max_price_after_stop_loss(self, stock_code: str, stop_loss_time: int, stop_loss_price: float):
        """
        计算止损后5分钟内的最高价格
        
        Args:
            stock_code: 股票代码
            stop_loss_time: 止损时间戳
            stop_loss_price: 止损价格
        """
        try:
            # 将时间戳转换为datetime对象
            stop_loss_dt = datetime.datetime.fromtimestamp(stop_loss_time)
            trade_date = stop_loss_dt.strftime("%Y%m%d")
            
            # 计算5分钟后的时间
            end_time_dt = stop_loss_dt + datetime.timedelta(minutes=5)
            
            # 如果5分钟后超过交易时间，则调整到当日收盘时间
            market_close_time = stop_loss_dt.replace(hour=15, minute=0, second=0, microsecond=0)
            if end_time_dt > market_close_time:
                end_time_dt = market_close_time
            
            end_time_str = end_time_dt.strftime("%Y%m%d%H%M%S")
            start_time_str = stop_loss_dt.strftime("%Y%m%d%H%M%S")
            
            print(f"🔍 分析止损后价格走势: {stock_code}")
            print(f"   止损时间: {stop_loss_dt.strftime('%Y-%m-%d %H:%M:%S')}")
            print(f"   止损价格: {stop_loss_price}")
            print(f"   分析区间: {start_time_str} 到 {end_time_str}")
            
            # 下载并获取tick数据
            try:
                xtdata.download_history_data(
                    stock_code=stock_code,
                    period="tick",
                    start_time=trade_date,
                    end_time=trade_date
                )
                time.sleep(1.5)  # 等待下载完成
                
                # 获取本地数据
                data = xtdata.get_local_data(
                    stock_list=[stock_code],
                    period='tick',
                    start_time=trade_date,
                    end_time=trade_date
                )
                
                if not data or stock_code not in data or data[stock_code].empty:
                    print(f"❌ 无法获取 {stock_code} 的tick数据")
                    return
                
                df = data[stock_code].copy()
                
                # 识别时间列和价格列
                time_col = next((c for c in df.columns if 'time' in c.lower()), None)
                price_col = next((c for c in ['close', 'lastPrice', 'price', 'last', 'current'] if c in df.columns), None)
                
                if not time_col or not price_col:
                    print(f"❌ 无法识别 {stock_code} 的时间列或价格列")
                    return
                
                # 处理时间格式
                if str(df[time_col].dtype) in ('int64', 'float64'):
                    # 毫秒时间戳
                    df['__time__'] = pd.to_datetime(df[time_col], unit='ms') + pd.Timedelta(hours=8)
                else:
                    # 尝试其他时间格式
                    try:
                        df['__time__'] = pd.to_datetime(df[time_col], format='%Y%m%d%H%M%S', errors='coerce')
                    except Exception:
                        df['__time__'] = pd.to_datetime(df[time_col], errors='coerce')
                
                # 过滤有效数据
                df = df[df['__time__'].notna()].copy()
                df = df[df[price_col] > 0].copy()  # 过滤价格大于0的数据
                
                if df.empty:
                    print(f"❌ {stock_code} 过滤后无有效数据")
                    return
                
                # 筛选止损后5分钟内的数据
                mask = (df['__time__'] >= stop_loss_dt) & (df['__time__'] <= end_time_dt)
                period_data = df[mask].copy()
                
                if period_data.empty:
                    print(f"❌ {stock_code} 止损后5分钟内无数据")
                    return
                
                # 计算最高/最低/最终价格
                max_price = float(period_data[price_col].max())
                min_price = float(period_data[price_col].min())
                current_price = float(period_data[price_col].iloc[-1]) if not period_data.empty else float(stop_loss_price)
                
                # 计算价格变化
                max_change = max_price - stop_loss_price
                min_change = min_price - stop_loss_price
                final_change = current_price - stop_loss_price
                
                # 输出分析结果
                print(f"📊 止损后5分钟价格分析结果:")
                print(f"   最高价格: {max_price:.4f} (涨幅: {max_change:.4f})")
                print(f"   最低价格: {min_price:.4f} (跌幅: {min_change:.4f})")
                print(f"   最终价格: {current_price:.4f} (变化: {final_change:.4f})")
                print(f"   数据点数: {len(period_data)}")
                
                # 判断是否错过反弹机会
                if max_change > 0.002:  # 如果最高涨幅超过0.2%
                    print(f"⚠️  错过反弹机会! 最高涨幅: {max_change:.4f}")
                
 
                # 返回值供统计持久化使用
                return {
                    "high_5m": max_price,
                    "low_5m": min_price,
                    "last_5m": current_price,
                    "points_5m": int(len(period_data))
                }
            except Exception as e:
                print(f"❌ 分析止损后价格走势失败: {e}")
                traceback.print_exc()
                return None
        except Exception as e:
            print(f"❌ 计算止损后最高价格异常: {e}")
            traceback.print_exc()
            return None

    ##测试
    def test_orders(self):
        now_price = 2.311
        stock_span = {stock["all_code"]: stock["span"] for stock in settings.STOCK_CODE}
        filled_orders_sorted, no_filled_orders, stocks = self.get_orders()

        # 检查是否有相同股票的待买入挂单（只检查买入单）
        for order in no_filled_orders:
            stock_code = order.stock_code
            sell_price = order.price
            remark_str = order.order_remark
            buy_id = 0
            sell_type = 1
            order_type = 1
            buy_price = 0
            down_price = 0
            span = stock_span.get(stock_code)
            try:
                remark = json.loads(remark_str)
                buy_id = remark.get("buy_id", 0)
                sell_type = remark.get("sell_type", 1)
                order_type = remark.get("order_type", 1)
                buy_price = remark.get("buy_price", 0)
                print(f"")
            except json.JSONDecodeError as e:
                pass
            except KeyError as e:
                pass
            if buy_id>0:
                if sell_type==1:##1为普通单2为区间单
                    if order_type == 1:
                        down_price = float(buy_price) - float(span * 3)
                    if order_type == 2:
                        down_price = float(buy_price) - float(span * 3)
                        ##查询相同buy_id的另外一笔是否成交
                        if self.check_other_order_filled(filled_orders_sorted, buy_id, order.order_sysid):
                            down_price = float(buy_price) - float(span * 2)
                if sell_type==2:
                    down_price = float(buy_price) - float(span * 2)
                print(f"订单 {order.order_sysid},止盈等级{order_type}买入价格{buy_price},止盈价格{sell_price},最新价格 {now_price}止损{down_price}")
                if float(now_price) <= float(down_price):
                    print(f"订单 {order.order_sysid}止损了")

    def test_addorder(self):
        order_remark = {
            "buy_id": 1,
            "sell_type": 1,
            "order_type": 1,  ##2级止盈
            "buy_price": 2.317,
        }
        order_remark_string = json.dumps(order_remark, ensure_ascii=False)
        price = float(2.317) + float(0.002) * 1
        self.place_reverse_order(
            stock_code="513090.SH",
            price=price,  # 市价单（或指定价格）
            volume=1000 / 2,
            direction=xtconstant.STOCK_SELL,  # 卖出
            order_remark=order_remark_string
        )
    @staticmethod
    def check_other_order_filled(filled_orders, buy_id, current_order_sysid):
        """
        查询相同buy_id的另外一笔订单是否已成交
        :param filled_orders: 已成交订单列表
        :param buy_id: 买入订单ID
        :param current_order_sysid: 当前订单ID（排除自己）
        :return: True如果其他订单已成交，False如果未成交
        """
        try:
            # 查找相同buy_id的其他已成交订单
            for order in filled_orders:
                if order.order_sysid == current_order_sysid:
                    continue  # 跳过当前订单

                try:
                    # 解析订单备注信息
                    remark_str = order.order_remark
                    if remark_str:
                        remark = json.loads(remark_str)
                        order_buy_id = remark.get("buy_id")

                        # 如果找到相同buy_id的订单且已成交
                        if order_buy_id == buy_id:
                            print(f"找到相同buy_id {buy_id} 的订单 {order.order_sysid} 已成交")
                            return True
                except (json.JSONDecodeError, KeyError) as e:
                    # 如果解析备注失败，跳过这个订单
                    continue

            print(f"未找到相同buy_id {buy_id} 的其他已成交订单")
            return False

        except Exception as e:
            print(f"查询相同buy_id订单时出错: {e}")
            return False